<template>
  <div class="home" @click="rightOff = false">
    <div class="container" :style="dialogOff ? 'filter: blur(1px)' : ''">
      <header>
        <div class="logo"></div>
        <h2>家谱分析</h2>
        <div class="form-wrapper">
          <el-input class="input-with-select" @keydown.enter="getData()" v-model="input" clearable  placeholder="请输入内容">
            <el-button slot="append" @click="getData()">搜索</el-button>
          </el-input>
        </div>
      </header>
      <div class="section-main">
        <div class="left">
          <div class="left-content" v-for="(item, key) in infoList" :key="key">
            <a class="closebtn el-icon-circle-close" @click="removeInfo(key)" title="关闭"></a>
            <div class="img-wrapper default">
              <img :src="item['header']['photo']" alt="">
            </div>
            <div class="content-header">
              <div><i class="icon icon-name"></i><span :class="[item['header']['sex'] ? 'men': 'women']">{{item['header']['xm']}}</span></div>
              <div><i class="icon icon-zhen"></i><span>{{item['header']['zjhm']}}</span></div>
            </div>
            <ul class="content-list">
              <li class="item" v-for="(val, key) in item['list']" :key="key">
                <label class="label">{{val['label']}}</label>
                <span class="value">{{val['value']}}</span>
              </li>
            </ul>
            <div class="btn-wrapper">
              <a class="btn" :href="getUrl(input)" target="_blank">查看详情</a>
            </div>
          </div>
        </div>
        <div class="right">
          <echart-view 
            chartId="echart_view" 
            :options="echartData" 
            @contextmenu="getContextMenu"
            @clickEcharts="getClick">
          </echart-view>
        </div>
      </div>
    </div>
    <div class="site-right" v-show="rightOff" :style="rightStyle">
      <div class="item" @click="getAddInfoList(rightId)">查看基本信息</div>
      <div class="item" @click="getAddData(rightId)">拓展关系</div>
      <div class="item" @click="getOtherData(rightId)">查看关系</div>
      <a class="item" :href="getUrl(rightId)" target="_blank">查看详细信息</a>
    </div>
    <dialog-view 
      v-show="dialogOff"
      @dialogOff="changeOff"
      :data="dialogData"
      :imgUrl="imgBaseUrl">
    </dialog-view>
  </div>
</template>

<script>
import { getUrlParam } from '../util/tools.js'
import { mockdata } from '../mock/mockdata.js'
import { apiGetReSelect, apiGetRelations, apiGetPersonInfo, apiGetApplication, apiGetRelationData } from '../api/api.js'
import echartView from '../components/echart.vue'
import dialogView from '../components/dialogview.vue'

export default {
  components: {
    echartView,
    dialogView
  },
  data () {
    return {
      token: '',
      applicationUrl: {},
      input: '430703198411060577',
      imgBaseUrl: process.env.NODE_ENV === 'development' ? 'http://192.168.0.181:8190/family/person/getPhoto?zjhm=' : '/family/person/getPhoto?zjhm=',
      headerLabel: {
        xm: '',
        zjhm: '',
        photo: '',
      },
      infoListlabel: {
        'hyzk': '婚姻状况',
        'mz': '民族',
        'whcd': '文化程度',
        'zzxz': '出生地详址',
        'xz': '住址详址'
      },
      infoList: {
        'id': {
          header: {
            sex: true,
            xm: '',
            zjhm: '',
            photo: '',
          },
          list: [
            { label: '婚姻状况', value: '' },
            { label: '民族', value: '无' },
            { label: '文化程度', value: '' },
            { label: '出生地详址', value: '' },
            { label: '住址详址', value: '' }
          ]
        }
      },
      imgMain: require('../assets/img/bg-main.png'),
      imgOther: require('../assets/img/bg-other.png'),
      iconMen: require('../assets/img/icon-men.png'),
      iconFamle: require('../assets/img/icon-famle.png'),
      imgDefault: require('../assets/img/img-default.jpg'),
      sex: '',
      birdate: '',
      relation: {},
      _rdata: { data: [], links: [] },
      echartData: mockdata.echartData,
      canvas: '',
      context: '',
      // right 右键点击弹出的弹窗变量
      rightOff: false,
      rightStyle: '',
      rightId: '',
      dialogOff: false,
      dialogData: {
        info: {
          rela: '',
          target: {
            id: '',
            name: '',
            sex: '',
            age: ''
          },
          source: {
            id: '',
            name: '',
            sex: '',
            age: ''
          }
        },
        list: {}
      }
    }
  },
  mounted() {
    this.getToken();
    this.getRelation();
    this.getApplictionUrl();
    this.getData();
  },
  methods: {
    // 获取url中的token
    getToken() {
      this.token = getUrlParam('token') ? getUrlParam('token') : '';
    },
    // 获取应用地址
    getApplictionUrl() {
      apiGetApplication().then(res => {
        // console.log(res);
        Object.assign(this.applicationUrl, res);
      })
    },
    // 获取关系列表
    getRelation() {
      this.relation = {};
      apiGetReSelect().then(res => {
        if(!res) {
          return
        }
        for(let i in res) {
          this.$set(this.relation, i, res[i]);
        }
      })
    },
    // 计算年龄
    getAge(birthday) {
      if(!birthday) {
        return ''
      }
      // return new Date((new Date().getTime() - parseInt(birthday))).getUTCFullYear() - 1970
      return new Date().getFullYear() - new Date(parseInt(birthday)).getFullYear() + '岁'
    },
    getSex(sex) {
      if(!sex) {
        return ''
      }
      return sex === '男' ? this.iconMen : this.iconFamle
    },
    // canvas绘制圆形图片
    getImgData(imgSrc) {
      let _this = this;
      return new Promise((resolve) => {
        const canvas = document.createElement('canvas');
        const contex = canvas.getContext('2d');
        const img = new Image();
        img.crossOrigin = '';
        let radius, diameter, center;
        img.onload = function() {
          diameter = Math.min(img.width, img.height);
          radius = diameter / 2;
          center = { x: img.width / 2, y: img.height / 2};
          canvas.width = diameter;
          canvas.height = diameter;
          contex.clearRect(0, 0, diameter, diameter);
          contex.save();
          contex.beginPath();
          contex.arc(radius, radius, radius, 0, 2 * Math.PI); //画出圆
          contex.clip(); //裁剪上面的圆形
          contex.drawImage(img, center.x - radius, center.y - radius, diameter, diameter, 0, 0, diameter, diameter); // 在刚刚裁剪的园上画图
          contex.restore(); // 还原状态
          resolve(canvas.toDataURL('image/png', 1))
        }
        img.onerror = function() {
          let eImg = new Image();
          img.src = _this.imgDefault;
          let radius, diameter, center;
          img.onload = function() {
            diameter = Math.min(img.width, img.height);
            radius = diameter / 2;
            center = { x: img.width / 2, y: img.height / 2};
            canvas.width = diameter;
            canvas.height = diameter;
            contex.clearRect(0, 0, diameter, diameter);
            contex.save();
            contex.beginPath();
            contex.arc(radius, radius, radius, 0, 2 * Math.PI); //画出圆
            contex.clip(); //裁剪上面的圆形
            contex.drawImage(img, center.x - radius, center.y - radius, diameter, diameter, 0, 0, diameter, diameter); // 在刚刚裁剪的园上画图
            contex.restore(); // 还原状态
            resolve(canvas.toDataURL('image/png', 1))
          }
        }
        img.src = imgSrc;
      });
    },
    // 获取当前人员信息与家族关系
    getData(id) {
      // 判断是否查看当前人员信息
      let _id = this.input;
      if(id) {
        _id = id;
        this.input = _id;
      }
      this.echartData['data'] = [];
      this.echartData['links'] = [];
      this.infoList = {};
      apiGetRelations(_id).then(res => {
        let _resdata = res.data;
        // console.log(_resdata)
        if(!_resdata || typeof _resdata == 'string') {
          this.$message.error(_resdata);
          return;
        }
        let _item = {};
        _item['header'] = {};
        _item['list'] = [];
        for(let i in this.headerLabel) {
          _item['header'][i] = _resdata[i] ? _resdata[i] : '无';
        }
        _item['header']['sex'] = _resdata['xb'] ? (_resdata['xb'] == '男' ? true : false) : '';
        for(let i in this.infoListlabel) {
          let _val = _resdata[i] ? _resdata[i] : '无';
          if(i == 'csrq') {
            _val = _resdata[i] ? new Date(parseInt(_resdata[i])).Format('yyyy-MM-dd') : '无';
          }
          _item['list'].push({ label: this.infoListlabel[i], value: _val});
        }
        this.$set(this.infoList, this.input,_item);

        // 人物关系
        let _this = this;
        _this.getImgData(_resdata['photo']).then((img) => {
          _this.echartData['data'].push({ 
            name: _resdata['xm'], 
            value: {
              id: _resdata['zjhm'],
              symbol: img,
              symbolSize: 'center',
              sex: _this.getSex(_resdata['xb']),
              age: _this.getAge(_resdata['csrq'])
            } 
          });
        }).catch(error => {
          _this.echartData['data'].push({ 
            name: _resdata['xm'], 
            value: {
              id: _resdata['zjhm'],
              symbol: '',
              symbolSize: 'center',
              sex: _this.getSex(_resdata['xb']),
              age: _this.getAge(_resdata['csrq'])
            } 
          });
        });
        let _relation = _resdata['relations'];
        if(!_relation || _relation.length < 1) {
          return;
        }
        for(let i in _relation) {
          if(_relation[i].length < 1) {
            continue
          }
          _relation[i].forEach(elem => {
            let text = elem.split('|'),
                sex = '',
                birdate = '';
            apiGetPersonInfo(text[0]).then(res => {
              if(res.data.success) {
                sex = res.data.data[0]['xb'];
                birdate = res.data.data[0]['csrq'];
              }
              _this.getImgData(this.imgBaseUrl+text[0]).then((img) => {
                _this.echartData['data'].push({ 
                  name: text[1], 
                  value: {
                    id: text[0],
                    symbol: img,
                    symbolSize: 'child',
                    sex: _this.getSex(sex),
                    age: _this.getAge(birdate)
                  } 
                });
              }).catch(error => {
                _this.echartData['data'].push({ 
                  name: text[1], 
                  value: {
                    id: text[0],
                    symbol: '',
                    symbolSize: 'child',
                    sex: _this.getSex(sex),
                    age: _this.getAge(birdate)
                  } 
                });
              })
            }).catch(error => {
               _this.getImgData(this.imgBaseUrl+text[0]).then((img) => {
                _this.echartData['data'].push({ 
                  name: text[1], 
                  value: {
                    id: text[0],
                    symbol: img,
                    symbolSize: 'child',
                    sex: _this.getSex(sex),
                    age: _this.getAge(birdate)
                  } 
                });
              }).catch(error => {
                _this.echartData['data'].push({ 
                  name: text[1], 
                  value: {
                    id: text[0],
                    symbol: '',
                    symbolSize: 'child',
                    sex: _this.getSex(sex),
                    age: _this.getAge(birdate)
                  } 
                });
              })
            })
            _this.echartData['links'].push({ 
              source: _resdata['xm'], 
              target: text[1], 
              value: this.relation[i], 
              other: { 
                id: text[0], ck: text[2], 
                idp: _resdata['zjhm'], 
                sexp: _resdata['xb'] ? _resdata['xb'] :'',
                agep: _this.getAge(_resdata['csrq'])
              } 
            });  
            // _this.echartData['links'].push({ source: _resdata['xm'], target: text[1], value: this.relation[i], other: { id: text[0], rela: text[2] } });           
          });
        }
      })  
    },
    // 右键点击事件
    getContextMenu(e) {
      this.rightOff = true;
      this.rightStyle = 'top:' + parseInt(e.event['offsetY']+60) + 'px; left: '+ parseInt(e.event['offsetX']+20) + 'px';
      this.rightId = e.value;
    },
    // 查看基本信息点击事件
    getAddInfoList(id) {
      apiGetPersonInfo(id).then(res => {
        let _resdata = res.data;
        if(!_resdata.success) {
          this.$message.error('基本信息'+_resdata.message);
          return;
        }
        // console.log(_resdata);
        let _rdata = _resdata['data'][0];
        let _item = {};
        _item['header'] = {};
        _item['list'] = [];
        for(let i in this.headerLabel) {
          _item['header'][i] = _rdata[i] ? _rdata[i] : '无';
        }
        _item['header']['sex'] = _rdata['xb'] ? (_rdata['xb'] == '男' ? true : false) : '';
        _item['header']['zjhm'] = _rdata['sfzh'];
        _item['header']['photo'] = this.imgBaseUrl + _rdata['sfzh'];
        for(let i in this.infoListlabel) {
          let _val = _rdata[i] ? _rdata[i] : '无';
          if(i == 'csrq') {
            _val = _rdata[i] ? new Date(parseInt(_rdata[i])).Format('yyyy-MM-dd') : '无';
          }
          _item['list'].push({ label: this.infoListlabel[i], value: _val});
        }
        this.$set(this.infoList, id,_item);
      })
    },
    // 扩展关系
    getAddData(id) {
      // 判断是否是当前人员
      if(id == this.input) {
        return ;
      }
      apiGetRelations(id).then(res => {
        let _resdata = res.data;
        // console.log(_resdata)
        if(!_resdata || typeof _resdata == 'string') {
          this.$message.error(_resdata);
          return;
        }

        // 人物关系
        let _this = this;
        let _relation = _resdata['relations'];
        if(!_relation || _relation.length < 1) {
          return;
        }
        // console.log(_relation)
        for(let i in _relation) {
          if(_relation[i].length < 1) {
            continue
          }
          _relation[i].forEach(elem => {
            let text = elem.split('|'),
                sex = '',
                birdate = '';
                // off = false;   // 判断是否存在数组中  true： 存在  false： 不存在
            // 判断是否是当前人员
            if(text[0] != this.input) {
              _this.echartData['links'].push({ 
                source: _resdata['xm'], 
                target: text[1], 
                value: this.relation[i], 
                other: { 
                  id: text[0], ck: text[2], 
                  idp: _resdata['zjhm'], 
                  sexp: _resdata['xb'] ? _resdata['xb'] :'',
                  agep: _this.getAge(_resdata['csrq'])
                } 
              });           
              // 判断该人员是否已经存在于改家谱关系中
              for(let i = 0, len = _this.echartData['data'].length; i < len; i++) {
                // console.log(_this.echartData['data'][i]['value']['id'] == text[0])
                if(_this.echartData['data'][i]['value']['id'] == text[0]) {
                  // off = true;
                  return
                }
              }
              apiGetPersonInfo(text[0]).then(res => {
                if(res.data.success) {
                  sex = res.data.data[0]['xb'];
                  birdate = res.data.data[0]['csrq'];
                }
                _this.echartData['data'].push({ 
                  name: text[1], 
                  value: {
                    id: text[0],
                    symbol: this.imgBaseUrl+text[0],
                    symbolSize: 'child',
                    sex: _this.getSex(sex),
                    age: _this.getAge(birdate)
                  } 
                });
              }).catch(error => {
                _this.echartData['data'].push({ 
                  name: text[1], 
                  value: {
                    id: text[0],
                    symbol: this.imgBaseUrl+text[0],
                    symbolSize: 'child',
                    sex: _this.getSex(sex),
                    age: _this.getAge(birdate)
                  } 
                });
              })
            }
          });
        }
      })  
    },
    // 查看关系
    getOtherData(id) {
      // 判断是否是当前人员
      if(id == this.input) {
        return ;
      }
      this.getData(id);
    },
    // 获取点击事件
    getClick(data) {
      // console.log(data);
      let _this = this;
      this.dialogData['info'] = {};
      this.$set(this.dialogData['info'], 'target', { id: data['other'].idp, name: data.source, sex: this.changeSex(data['other'].sexp), age: data['other'].agep });
      this.$set(this.dialogData['info'], 'source', { id: data['other'].id, name: data.target, sex: '', age: '' });
      this.$set(this.dialogData['info'], 'rela', data.value);
      // 获取个人信息
      apiGetPersonInfo(data['other'].id).then(res => {
        let _resdata = res.data;
        if(!_resdata.success) {
          return;
        }
        // console.log(_resdata);
        let _rdata = _resdata['data'][0];
        this.$set(this.dialogData['info']['source'], 'sex', _this.changeSex(_rdata['xb']));
        this.$set(this.dialogData['info']['source'], 'age', _this.getAge(_rdata['csrq']));
      });

      // 获取详细信息
      let params = {
        ids: data['other']['id'] ? data['other']['id'] : '',
        code: data['other']['ck'] ? data['other']['ck'] : ''
      }
      this.dialogData['list'] = {};
      apiGetRelationData(params).then(res => {
        let _resdata = res;
        // console.log(_resdata);
        if(!_resdata.success) {
          this.$message.error(_resdata.msg)
          return 
        }
        // 关系详情弹窗 弹出
        this.dialogOff = true;
        let _result = _resdata['result'],
            _header = _resdata['header'];
        if(_result.length < 1 || !_result) {
          return 
        }
        for(let k in _header) {
          this.$set(_this.dialogData['list'], _header[k], _result[0][k] ? _result[0][k] : '')
        }
      })
    },
    changeOff(val) {
      this.dialogOff = val;
    },
    getUrl(id) {
      let token = 'token';
      let url = this.applicationUrl['superdocument'] ? this.applicationUrl['superdocument'] : '';
      return url.replace(/\<<zjhm>>/, id).replace(/\<<token>>/, token);
    },
    // 移除详细信息
    removeInfo(id) {
      this.$delete(this.infoList, id);
    },
    // 判断显示男女图标
    changeSex(sex) {
      if(sex) {
        return sex == '男' ? 'men' : 'women'
      }
      return ''
    }
  }
}
</script>

<style lang="stylus" scoped>
@import "../assets/style/home.styl";
</style>
<style lang="stylus">
.el-input__inner{
  font-size 14px
  color #fff
  border: 2px solid #0febff
  border-radius 0 !important
  background-color transparent
  &:focus, &:hover{
    border-color rgba(15, 235, 255, .8)
  }
}
.el-input-group__append{
  color #fff
  background-color #0febff
  border: none
  border-radius 0
  cursor pointer
}
.el-input-group{
  vertical-align middle
}
@media screen and (max-height: 900px) {
  .el-input__inner{
    height 30px
    line-height 30px
  }
}
</style>
